<template>
  <div>
    <a-card title="销售开单">
      <a-spin :spinning="loading">
        <a-form-model
          ref="form"
          :model="form"
          :rules="rules"
          :label-col="{ span: 8 }"
          :wrapper-col="{ span: 16 }"
        >
          <a-row>
            <a-col :span="6" style="width: 320px">
              <a-form-model-item prop="number" label="销售编号">
                <a-input v-model="form.number" />
              </a-form-model-item>
            </a-col>
            <a-col :span="6" style="width: 320px">
              <a-form-model-item prop="warehouse" label="仓库">
                <a-select v-model="form.warehouse" style="width: 100%">
                  <a-select-option
                    v-for="item in warehouseItems"
                    :key="item.id"
                    :value="item.id"
                  >
                    {{ item.name }}
                  </a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
            <a-col :span="6" style="width: 320px">
              <a-form-model-item prop="client" label="客户">
                <a-select
                  showSearch
                  v-model="form.client"
                  style="width: 100%"
                  :filterOption="filterOption"
                >
                  <a-select-option
                    v-for="item in clientsItems"
                    :key="item.id"
                    :value="item.id"
                  >
                    {{ item.name }}
                  </a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
            <a-col :span="6" style="width: 320px">
              <a-form-model-item prop="handler" label="经手人">
                <a-select v-model="form.handler" style="width: 100%">
                  <a-select-option
                    v-for="item in handlerItems"
                    :key="item.id"
                    :value="item.id"
                  >
                    {{ item.name }}
                  </a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
            <a-col :span="6" style="width: 320px">
              <a-form-model-item prop="handle_time" label="处理日期">
                <!-- <a-date-picker v-model="form.handle_time" valueFormat="YYYY-MM-DD" style="width: 100%" /> -->
                <a-date-picker
                  v-model="form.handle_time"
                  valueFormat="YYYY-MM-DD HH:mm:ss"
                  style="width: 100%"
                  disabled
                />
              </a-form-model-item>
            </a-col>
            <a-col :span="6" style="width: 320px">
              <a-form-model-item prop="remark" label="备注">
                <a-input v-model="form.remark" allowClear />
              </a-form-model-item>
            </a-col>
          </a-row>
        </a-form-model>

        <a-divider orientation="left">产品信息</a-divider>

        <div>
          <a-row gutter="16">
            <a-space>
              <a-button
                type="primary"
                @click="openMaterialModal"
                style="float: right"
                >添加产品</a-button
              >
            </a-space>
          </a-row>
          <div style="margin-top: 16px">
            <a-table
              bordered
              rowKey="id"
              size="middle"
              :columns="columns"
              :data-source="goodsData"
              :pagination="false"
            >
              <div slot="specification" slot-scope="value, item, index">
                <div v-if="item.isTotal">{{ value }}</div>
                <a-input
                  v-else
                  v-model="item.specification"
                  :min="0"
                  size="small"
                  placeholder=""
                  bordered="{false}"
                  @input="fetchHistoricalPrice(item)"
                ></a-input>
              </div>
              <div slot="quantity" slot-scope="value, item, index">
                <div v-if="item.isTotal">{{ value }}</div>
                <a-input-number
                  v-else
                  v-model="item.quantity"
                  :min="0"
                  size="small"
                  placeholder=""
                  bordered="{false}"
                ></a-input-number>
              </div>
              <div slot="unit_weight" slot-scope="value, item, index">
                <div v-if="item.isTotal">{{ value }}</div>
                <a-input
                  v-else
                  v-model="item.unit_weight"
                  size="small"
                  @change="calculateTotal(item, 'unit_weight')"
                ></a-input>
              </div>
              <div slot="material_unit_price" slot-scope="value, item, index">
                <div v-if="item.isTotal">{{ value }}</div>
                <a-input-number
                  v-else
                  v-model="item.material_unit_price"
                  :min="0"
                  size="small"
                ></a-input-number>
              </div>
              <div slot="material_amount" slot-scope="value, item, index">
                <div>{{ value }}</div>
              </div>
              <div slot="unit_strip_count" slot-scope="value, item, index">
                <div v-if="item.isTotal">{{ value }}</div>
                <a-input
                  v-else
                  v-model="item.unit_strip_count"
                  size="small"
                  @change="calculateTotal(item, 'unit_strip_count')"
                ></a-input>
              </div>
              <div slot="ironing_unit_price" slot-scope="value, item, index">
                <div v-if="item.isTotal">{{ value }}</div>
                <a-input-number
                  v-else
                  v-model="item.ironing_unit_price"
                  :min="0"
                  size="small"
                ></a-input-number>
              </div>
              <div slot="ironing_amount" slot-scope="value, item, index">
                <div>{{ value }}</div>
              </div>
              <div slot="totalAmount" slot-scope="value, item, index">
                <div>{{ value }}</div>
              </div>
              <div slot="notes" slot-scope="value, item, index">
                <div v-if="item.isTotal">{{ value }}</div>
                <a-input
                  v-else
                  v-model="item.notes"
                  :min="0"
                  size="small"
                  placeholder=""
                  bordered="{false}"
                ></a-input>
              </div>
              <div slot="action" slot-scope="value, item, index">
                <a-button-group v-if="!item.isTotal" size="small">
                  <a-button type="danger" @click="removeMaterial(item)"
                    >移除</a-button
                  >
                </a-button-group>
              </div>
            </a-table>
          </div>
        </div>
        <a-divider orientation="left">账单信息</a-divider>
        <div>
          <a-row gutter="16">
            <a-col :span="4">
              <a-form-model-item
                prop="discount"
                label="整单折扣"
                :label-col="{ span: 24 }"
                :wrapper-col="{ span: 24 }"
              >
                <a-input v-model="form.discount" style="width: 100%" />
              </a-form-model-item>
            </a-col>

            <a-col :span="4">
              <a-form-model-item
                prop="other_amount"
                label="其他费用"
                :label-col="{ span: 24 }"
                :wrapper-col="{ span: 24 }"
              >
                <a-input v-model="form.other_amount" style="width: 100%" />
              </a-form-model-item>
            </a-col>
            <a-col :span="4">
              <a-form-model-item
                label="总计金额(元)"
                :label-col="{ span: 24 }"
                :wrapper-col="{ span: 24 }"
              >
                <a-input
                  :value="totalAmount"
                  :disabled="true"
                  style="width: 100%"
                />
              </a-form-model-item>
            </a-col>
            <a-col :span="4">
              <a-form-model-item
                label="总计金额(大写)"
                :label-col="{ span: 24 }"
                :wrapper-col="{ span: 24 }"
              >
                <a-input
                  :value="convertCurrency(totalAmount)"
                  :disabled="true"
                  style="width: 100%; color: black"
                />
              </a-form-model-item>
            </a-col>
          </a-row>

          <a-row gutter="16">
            <a-col :span="4">
              <a-form-model-item
                label="结算账户"
                :label-col="{ span: 24 }"
                :wrapper-col="{ span: 24 }"
              >
                <a-select v-model="form.account" style="width: 100%">
                  <a-select-option
                    v-for="Account in accountsItems"
                    :key="Account.id"
                    :value="Account.id"
                  >
                    {{ Account.name }}
                  </a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
            <a-col :span="4">
              <a-form-model-item
                label="实收金额(元)"
                :label-col="{ span: 24 }"
                :wrapper-col="{ span: 24 }"
              >
                <a-input
                  v-model="sales_account_item.collection_amount"
                  style="width: 100%"
                />
              </a-form-model-item>
            </a-col>
            <a-col :span="4">
              <a-form-model-item
                label="本单欠款(元)"
                :label-col="{ span: 24 }"
                :wrapper-col="{ span: 24 }"
              >
                <a-input
                  :value="amountOwed"
                  :disabled="true"
                  style="width: 100%"
                />
              </a-form-model-item>
            </a-col>
            <a-col :span="4">
              <a-form-model-item
                label="欠款金额(大写)"
                :label-col="{ span: 24 }"
                :wrapper-col="{ span: 24 }"
              >
                <a-input
                  :value="convertCurrency(amountOwed)"
                  :disabled="true"
                  style="width: 100%; color: black"
                />
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row gutter="16">
            <a-col :span="4">
              <a-form-model-item
                label="是否已付款"
                :label-col="{ span: 24 }"
                :wrapper-col="{ span: 24 }"
              >
                <a-switch
                  v-model="form.qualification_status"
                  checkedChildren="已付款"
                  unCheckedChildren="未付款"
                />
              </a-form-model-item>
            </a-col>
          </a-row>
        </div>
      </a-spin>

      <div style="margin-top: 10px">
        <a-popconfirm title="确定开单吗?" @confirm="create">
          <a-button type="primary" :loading="loading">开单</a-button>
        </a-popconfirm>
      </div>
    </a-card>
    <!-- v-model="materialsSelectModalVisible" -->
    <materials-select-modal
      v-model="materialsSelectModalVisible"
      :warehouse="form.warehouse"
      @select="onSelectMaterial"
    ></materials-select-modal>
  </div>
</template>

<script>
import moment from "moment";
import { mapState } from "vuex";
import _ from "lodash";
import NP from "number-precision";
import { Create, Update, Destroy, List } from "@/api/common";
import { getSaleOrderNumber } from "@/api/data";
import { saleOrderCreate } from "@/api/sale";
import { convertCurrency, datetimeToString } from "@/utils/functions";
import { filterOption} from "@/utils/common";
import {
  userOption,
  clientsOption,
  warehousesOption,
  inventoriesOption,
  accountsOption,
} from "@/api/option";
import {
  canshu,
  xssl,
  columns,
  columns_dagong,
  rules,
  columnsAccount,
  calzhong_dg,
  calmianji_dg,
  calclAmount,
  caljgAmount_dg,
  callingjianDj_dg,
  calljtotalAmount_dg,
  calshifuAmount_dg,
} from "@/views/sale/saleCreate/js/data";
export default {
  components: {
    MaterialsSelectModal: () =>
      import("@/components/MaterialSelectModal/index"),
  },
  data() {
    return {
      user: this.$store.state.user,
      description: "新增",
      warehouseItems: [],
      handlerItems: [],
      jg_handlerItems: [],
      jgfltems: [],
      clientsItems: [],
      accountsItems: [],
      materialsSelectModalVisible: false,
      loading: false,
      model: {},
      form: {
        warehouse: "原材料仓库",
      },
      rules,
      columns,
      materialItems: [],
      columnsAccount,
      sales_account_items: [],
      sales_account_item: {},
      is_readSalePrice: false,
    };
  },
  computed: {
    totalAmount() {
      let totalAmount = 0;
      for (let item of this.materialItems) {
        // 对参与运算的 item.clsl 和 item.material_unit_price 进行检查
        if (
          item.total_weight !== undefined &&
          item.material_unit_price !== undefined
        ) {
          let amount = NP.plus(
            NP.times(item.total_weight, item.material_unit_price),
            NP.times(item.total_strip_count, item.ironing_unit_price)
          );
          totalAmount = NP.plus(totalAmount, amount);
        }
      }
      if (this.form.discount !== undefined) {
        totalAmount = NP.times(totalAmount, this.form.discount || 100, 0.01);
      }
      if (this.form.other_amount !== undefined) {
        totalAmount = NP.plus(totalAmount, this.form.other_amount || 0);
      }
      return NP.round(totalAmount, 2);
    },
    amountOwed() {
      return NP.minus(
        this.totalAmount,
        this.sales_account_item.collection_amount || 0
      );
    },
    goodsData() {
      // 统计合计
      let totalclAmount = 0,
        //普通表格部分
        material_amount = 0,
        ironing_amount = 0,
        all_total_weight = 0,
        all_total_strip_count = 0,
        total_material_amount = 0,
        total_ironing_amount = 0,
        total_quantity = 0,
        total_amount = 0;

      // for (let item of this.materialItems) {
      //   totalQuantity = NP.plus(totalQuantity, item.sales_quantity);
      //   let amount = NP.times(item.sales_quantity, item.sales_price);
      //   totalAmount = NP.plus(totalAmount, amount);
      // }
      for (let item of this.materialItems) {
        // for (let item of this.materialItems_mid) {
        //普通部分
        material_amount = NP.times(item.total_weight, item.material_unit_price);
        ironing_amount = NP.times(
          item.total_strip_count,
          item.ironing_unit_price
        );
        total_material_amount = NP.plus(total_material_amount, material_amount);
        all_total_weight = NP.plus(all_total_weight, item.total_weight);
        all_total_strip_count = NP.plus(
          all_total_strip_count,
          item.total_strip_count
        );
        total_ironing_amount = NP.plus(total_ironing_amount, ironing_amount);
        total_quantity = NP.plus(total_quantity, item.quantity);
        total_amount = NP.plus(total_amount, material_amount, ironing_amount);
        console.log("material_amount:" + material_amount);
      }
      return [
        ...this.materialItems,
        // ...this.materialItems_mid,
        {
          id: "-1",
          isTotal: true,
          name: "",
          // sales_quantity: totalQuantity,
          // totalAmount: `${totalAmount} * ${this.form.discount}% = ${NP.times(
          //   totalAmount,
          //   this.form.discount || 0,
          //   0.01
          // )}`,
          total_weight: all_total_weight,
          total_strip_count: all_total_strip_count,
          material_amount: total_material_amount,
          ironing_amount: total_ironing_amount,
          quantity: total_quantity,
          total_amount,
        },
      ];
    },
    accountsData() {
      // 统计合计
      let totalAmount = 0;
      for (let item of this.sales_account_items) {
        totalAmount = NP.plus(totalAmount, item.collection_amount);
      }
      return [
        ...this.sales_account_items,
        {
          id: "-1",
          isTotal: true,
          collection_amount: totalAmount,
        },
      ];
    },
  },
  methods: {
    // 根据客户、产品和型号尺寸获取历史价格
    fetchHistoricalPrice(item) {
      const client = this.form.client;
      const specification = item.specification;
      const name = item.name;
      List(
        { specification, client, name },
        `sales_SalesGoods/get_historical_price/`
      ).then((data) => {
        if (
          data.material_unit_price !== undefined &&
          data.ironing_unit_price !== undefined
        ) {
          item.material_unit_price = data.material_unit_price;
          item.ironing_unit_price = data.ironing_unit_price;
        } else {
          item.material_unit_price = 0;
          item.ironing_unit_price = 0;
        }
      });
    },
    setHandlerToLoggedInUser() {
      // 从 Vuex 中获取登录用户信息并设置为经手人
      if (this.user) {
        console.log(this.user);
        this.form.handler = this.user.userId;
      }
    },
    get_dict() {
      List({}, `dicts`).then((data) => {
        let res = data.results;
        this.jgfltems = res.filter((i) => i.code == "jgfltems")[0].dict_items;
      });
    },
    tableTypeChange() {
      if (this.form.tableType) {
        this.canshu.is_dagong_table = true;
      } else {
        this.canshu.is_dagong_table = false;
      }
    },
    // 将输入的内容与显示的内容进行匹配
    filterOption(value, option) {
      return filterOption(value, option) 
    },
    convertCurrency(money) {
      return convertCurrency(money);
    },
    initData() {
      //this.get_dict();
      // const arr=JSON.stringify(columns_dagong)
      // this.columns_dagong_data=JSON.parse(arr)
      this.columns_dagong_data = _.cloneDeep(columns_dagong);
      this.columns_dagong_data[5].children.splice(5, 1); //根据用料计量默认为重量删除面积
      this.columns_dagong_data[5].title = "用料（长宽厚：mm，重：kg）";
      this.resetForm();
      warehousesOption({ page_size: 999999, is_active: true }).then((data) => {
        this.warehouseItems = data.results;
        this.form.warehouse = this.warehouseItems[0].id;
      });
      userOption({ page_size: 999999, is_active: true }).then((data) => {
        this.handlerItems = data.results.filter((i) => i.is_manager == true);
        this.jg_handlerItems = data.results.filter(
          (i) => i.is_employee == true
        );
      });
      clientsOption({ page_size: 999999, is_active: true }).then((data) => {
        this.clientsItems = data.results;
      });
      accountsOption({ page_size: 999999, is_active: true }).then((data) => {
        this.accountsItems = data.results;
      });
      this.form.handle_time = datetimeToString(new Date());
    },
    handelAddAcount() {
      this.sales_account_items.push({
        id: this.sales_account_items.length + 1,
        account: "",
        collection_amount: 0,
      });
    },
    removeAccount(item) {
      this.sales_account_items = this.$functions.removeItem(
        this.sales_account_items,
        item
      );
    },
    changeAccount(value, item, idx) {
      let count = this.sales_account_items.filter((_item) => {
        return _item.account == value;
      });
      if (count.length > 1) {
        this.$message.warn("已添加过改结算账户!");
        this.sales_account_items[idx].account = "";
      }
    },
    openMaterialModal() {
      if (!this.form.warehouse) {
        this.$message.warn("请先选择仓库！");
        return false;
      }
      this.materialsSelectModalVisible = true;
    },
    zero_retail_price() {
      this.materialItems.forEach((e) =>
        e.clsl == 0 ? (e.material_unit_price = 0) : {}
      );
    },
    onSelectMaterial(item) {
      let index = this.materialItems.length + 1;
      this.materialItems.push({
        index: index,
        id: item.id,
        goods: item.goods,
        number: item.goods_number,
        name: item.goods_name,
        specification: item.specification,
        quantity: 0,
        unit_weight: 0,
        total_weight: 0,
        material_unit_price: 0,
        material_amount: 0,
        unit_strip_count: 0,
        total_strip_count: 0,
        ironing_unit_price: 0,
        ironing_amount: 0,
        total_amount: 0,
        sales_quantity: 0,
        sales_price: 0,
        notes: "",
      });
      this.materialItems = [...this.materialItems];
      console.log(this.materialItems);
    },
    removeMaterial(item) {
      let index = this.materialItems.findIndex(
        (_item) => _item.index == item.index
      );
      if (index != -1 && this.materialItems[index].id == item.id) {
        this.materialItems.splice(index, 1);
      }
      // 重新编号，从1开始
      this.materialItems = this.materialItems.map((item, index) => {
        return {
          ...item,
          index: index + 1, // 注意这里我们加了1
        };
      });
    },
    calculateTotal(item, propName) {
      try {
        const result = this.evaluateAdditionExpression(item[propName]);
        this.$set(
          item,
          propName === "unit_weight" ? "total_weight" : "total_strip_count",
          result
        );
      } catch (error) {
        console.error(`输入的表达式有误，请检查输入：`, error);
        // 给用户一个更友好的提示
        this.$message.error(`输入的表达式不合法，请输入合法的加法表达式。`);
      }
    },
    evaluateAdditionExpression(expression) {
      expression = expression.replace(/\s+/g, "");
      let sum = 0;
      let numStr = "";
      let lastChar = "";
      let i = 0;
      while (i < expression.length) {
        let char = expression.charAt(i);
        if ((char >= "0" && char <= "9") || char === ".") {
          numStr += char;
        } else if (char === "+") {
          if (numStr) {
            sum += parseFloat(numStr);
            numStr = "";
          }
        } else {
          throw new Error("Invalid character in expression");
        }
        lastChar = char;
        i++;
      }
      if (lastChar !== "+" || numStr) {
        sum += parseFloat(numStr);
      }
      sum = parseFloat(sum.toFixed(2));
      //console.log(`最终结果: ${sum}`);
      return sum;
    },

    create() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          if (this.materialItems.length == 0) {
            this.$message.warn("未添加产品");
            return false;
          }

          let sales_account_items = [];
          if (
            this.sales_account_item.account &&
            this.sales_account_item.collection_amount > 0
          ) {
            sales_account_items = [this.sales_account_item];
            this.form.account = this.sales_account_item.account;
          }

          this.loading = true;
          this.goodsData;
          let formData = {
            ...this.form,
            // sales_account_items: this.sales_account_items.map((item) => {
            //   delete item.id;
            //   return item;
            // }),
            sales_account_items,
            sales_goods_items: this.materialItems.map((item) => {
              return {
                goods: item.goods,
                sales_quantity: item.sales_quantity,
                sales_price: item.sales_price,
                sales_quantity: 1,
                specification: item.specification,
                quantity: item.quantity,
                unit_weight: item.unit_weight,
                total_weight: item.total_weight,
                material_unit_price: item.material_unit_price,
                material_amount: item.material_amount,
                unit_strip_count: item.unit_strip_count,
                total_strip_count: item.total_strip_count,
                ironing_unit_price: item.ironing_unit_price,
                ironing_amount: item.ironing_amount,
                total_amount: item.total_amount,
                notes: item.notes,
              };
            }),
          };
          saleOrderCreate(formData)
            .then((data) => {
              this.$message.success("创建成功");
              this.$router.push({ path: "/sale/sale_record" });
            })
            .finally(() => {
              this.loading = false;
            });
        }
      });
    },
    resetForm() {
      this.form = { other_amount: 0, tableType: false, unitType: false };
      this.sales_account_item = { collection_amount: 0 };
      getSaleOrderNumber().then((data) => {
        this.form = { ...this.form, number: data.number, discount: 100 };
      });
      this.materialItems = [];
      this.handelAddAcount();
    },
  },
  mounted() {
    this.initData();
    this.setHandlerToLoggedInUser(); // 调用方法将经手人设置为登录用户
  },
};
</script>
<style scoped>
::v-deep .ant-table-tbody > tr > td {
  padding: 1px !important;
}
</style>
